package org.jeecg.modules.demo.annualkeywork.controller;

import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jeecg.modules.demo.Constants;
import org.jeecg.modules.demo.annualkeywork.entity.*;
import org.jeecg.modules.demo.annualkeywork.service.ITobedoneAnnualKeyWorkService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.annualkeywork.vo.AnnualKeyWorkPage;
import org.jeecg.modules.demo.annualkeywork.service.IAnnualKeyWorkService;
import org.jeecg.modules.demo.annualkeywork.service.IKeyWorkDepartmentsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 年度重点工作
 * @Author: jeecg-boot
 * @Date:   2025-08-19
 * @Version: V1.0
 */
@Tag(name="年度重点工作")
@RestController
@RequestMapping("/annualkeywork/annualKeyWork")
@Slf4j
public class AnnualKeyWorkController {
	@Autowired
	private IAnnualKeyWorkService annualKeyWorkService;
	@Autowired
	private ITobedoneAnnualKeyWorkService tobedoneAnnualKeyWorkService;
	@Autowired
	private IKeyWorkDepartmentsService keyWorkDepartmentsService;
	
	/**
	 * 分页列表查询
	 *
	 * @param annualKeyWork
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "年度重点工作-分页列表查询")
	@Operation(summary="年度重点工作-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AnnualKeyWork>> queryPageList(AnnualKeyWork annualKeyWork,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<AnnualKeyWork> queryWrapper = QueryGenerator.initQueryWrapper(annualKeyWork, req.getParameterMap());
		Page<AnnualKeyWork> page = new Page<AnnualKeyWork>(pageNo, pageSize);
		IPage<AnnualKeyWork> pageList = annualKeyWorkService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param annualKeyWorkPage
	 * @return
	 */
	@AutoLog(value = "年度重点工作-添加")
	@Operation(summary="年度重点工作-添加")
    @RequiresPermissions("annualkeywork:yx_annual_key_work:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody AnnualKeyWorkPage annualKeyWorkPage) {
		System.out.println(annualKeyWorkPage);
		LoginUser sysUser=(LoginUser) SecurityUtils.getSubject().getPrincipal();
		annualKeyWorkPage.setRespondepart(sysUser.getOrgId());
		TobedoneAnnualKeyWork tobedoneAnnualKeyWork =TobedoneAnnualKeyWork.builder().build();
		System.out.println(annualKeyWorkPage);
		System.out.println(tobedoneAnnualKeyWork);
		BeanUtils.copyProperties(annualKeyWorkPage, tobedoneAnnualKeyWork);
		tobedoneAnnualKeyWorkService.saveMain(tobedoneAnnualKeyWork, annualKeyWorkPage.getKeyWorkDepartmentsList());
		return Result.OK(Constants.ADD_SUCCESS);
	}
	/**
	 *  编辑
	 *
	 * @param annualKeyWorkPage
	 * @return
	 */
	@AutoLog(value = "年度重点工作-编辑")
	@Operation(summary="年度重点工作-编辑")
    @RequiresPermissions("annualkeywork:yx_annual_key_work:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AnnualKeyWorkPage annualKeyWorkPage) {
		AnnualKeyWork annualKeyWork = new AnnualKeyWork();
		BeanUtils.copyProperties(annualKeyWorkPage, annualKeyWork);
		AnnualKeyWork annualKeyWorkEntity = annualKeyWorkService.getById(annualKeyWork.getId());
		if(annualKeyWorkEntity==null) {
			return Result.error(Constants.FIND_DATA_FAILURE);
		}
		annualKeyWorkService.updateMain(annualKeyWork, annualKeyWorkPage.getKeyWorkDepartmentsList());
		return Result.OK(Constants.EDIT_SUCCESS);
	}
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "年度重点工作-通过id删除")
	@Operation(summary="年度重点工作-通过id删除")
    @RequiresPermissions("annualkeywork:yx_annual_key_work:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		annualKeyWorkService.delMain(id);
		return Result.OK(Constants.DELETE_SUCCESS);
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "年度重点工作-批量删除")
	@Operation(summary="年度重点工作-批量删除")
    @RequiresPermissions("annualkeywork:yx_annual_key_work:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	@Transactional//事务处理注解
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.annualKeyWorkService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK(Constants.SOME_DELETE_SUCCESS);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "年度重点工作-通过id查询")
	@Operation(summary="年度重点工作-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AnnualKeyWork> queryById(@RequestParam(name="id",required=true) String id) {
		AnnualKeyWork annualKeyWork = annualKeyWorkService.getById(id);
		if(annualKeyWork==null) {
			return Result.error(Constants.FIND_DATA_FAILURE);
		}
		return Result.OK(annualKeyWork);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "重点工作配合部门通过主表ID查询")
	@Operation(summary="重点工作配合部门主表ID查询")
	@GetMapping(value = "/queryKeyWorkDepartmentsByMainId")
	public Result<List<KeyWorkDepartments>> queryKeyWorkDepartmentsListByMainId(@RequestParam(name="id",required=true) String id) {
		List<KeyWorkDepartments> keyWorkDepartmentsList = keyWorkDepartmentsService.selectByMainId(id);
		return Result.OK(keyWorkDepartmentsList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param annualKeyWork
    */
    @RequiresPermissions("annualkeywork:yx_annual_key_work:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AnnualKeyWork annualKeyWork) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<AnnualKeyWork> queryWrapper = QueryGenerator.initQueryWrapper(annualKeyWork, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<AnnualKeyWork> annualKeyWorkList = annualKeyWorkService.list(queryWrapper);

      // Step.3 组装pageList
      List<AnnualKeyWorkPage> pageList = new ArrayList<AnnualKeyWorkPage>();
      for (AnnualKeyWork main : annualKeyWorkList) {
          AnnualKeyWorkPage vo = new AnnualKeyWorkPage();
          BeanUtils.copyProperties(main, vo);
          List<KeyWorkDepartments> keyWorkDepartmentsList = keyWorkDepartmentsService.selectByMainId(main.getId());
          vo.setKeyWorkDepartmentsList(keyWorkDepartmentsList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "年度重点工作列表");
      mv.addObject(NormalExcelConstants.CLASS, AnnualKeyWorkPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("年度重点工作数据", "导出人:"+sysUser.getRealname(), "年度重点工作"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("annualkeywork:yx_annual_key_work:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@Transactional//事务处理注解
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<AnnualKeyWorkPage> list = ExcelImportUtil.importExcel(file.getInputStream(), AnnualKeyWorkPage.class, params);
              for (AnnualKeyWorkPage page : list) {
                  AnnualKeyWork po = new AnnualKeyWork();
                  BeanUtils.copyProperties(page, po);
                  annualKeyWorkService.saveMain(po, page.getKeyWorkDepartmentsList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 查询显示年度重点工作列表
	  *
	  * @return
	  */
	 @GetMapping(value = "/getAnnualKeyWorkList")
	 public Result<IPage<AnnualKeyWorkList>> getAnnualKeyWorkList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																 HttpServletRequest req) {
		 PageHelper.startPage(pageNo, pageSize);
		 List<AnnualKeyWorkList> annualKeyWorkList = annualKeyWorkService.queryKeyWorkList();
		 // 创建PageInfo对象
		 PageInfo<AnnualKeyWorkList> pageInfo = new PageInfo<>(annualKeyWorkList);
		 // 转换为IPage对象
		 IPage<AnnualKeyWorkList> page = new Page<>(pageNo, pageSize, pageInfo.getTotal());
		 page.setRecords(pageInfo.getList());

		 return Result.OK(page);
	 }
	 /*
	  * 汇报年度重点工作
	  * */
	 @RequestMapping(value = "/reportAnnualkeywork", method = RequestMethod.GET)
	 public Result<IPage<ReportAnnualKeyWork>> reportKeyWork(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {
		 PageHelper.startPage(pageNo, pageSize);
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<ReportAnnualKeyWork> ReportAnnualKeyWorkList = annualKeyWorkService.SelectKeyWorkList(sysUser.getOrgId());
		 // 创建PageInfo对象
		 PageInfo<ReportAnnualKeyWork> pageInfo = new PageInfo<>(ReportAnnualKeyWorkList);

		 // 转换为IPage对象
		 IPage<ReportAnnualKeyWork> page = new Page<>(pageNo, pageSize, pageInfo.getTotal());
		 page.setRecords(pageInfo.getList());
		 return Result.OK(page);
	 }

	 /**
	  *  汇报按钮
	  *
	  * @param reportAnnualKeyWork
	  * @return
	  */
	 @RequiresPermissions("annualkeyworkList:yx_annualkeyworkList:report")
	 @Transactional//事务处理注解
	 @RequestMapping(value = "/reportaction", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> reportaction(@RequestBody ReportAnnualKeyWork reportAnnualKeyWork) {
		 //实现状态从待汇报变为已汇报
		 System.out.println(reportAnnualKeyWork);
		 annualKeyWorkService.saveReportAnnualKeyWork(reportAnnualKeyWork);
		 return Result.OK(Constants.REPORT_SUCCESS);
	 }




	 /*
	  * 审批年度重点工作
	  * */
	 @RequestMapping(value = "/approvalKeyWorkList", method = RequestMethod.GET)
	 public Result<IPage<ApprovalAnnualKeyWork>> approvalKeyWork(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {

		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if(sysUser.getOrgId().equals(annualKeyWorkService.SelectApprovalKeyWorkListByRespondepartment())){
			 PageHelper.startPage(pageNo, pageSize);
			 List<ApprovalAnnualKeyWork> ApprovalAnnualKeyWorkList = annualKeyWorkService.SelectApprovalKeyWorkList();
			 // 创建PageInfo对象
			 PageInfo<ApprovalAnnualKeyWork> pageInfo = new PageInfo<>(ApprovalAnnualKeyWorkList);
			 // 转换为IPage对象
			 IPage<ApprovalAnnualKeyWork> page = new Page<>(pageNo, pageSize, pageInfo.getTotal());
			 page.setRecords(pageInfo.getList());
			 return Result.OK(page);
		 }
		 else{
			 return Result.OK(Constants.NO_DATA);
		 }

	 }

	 /**
	  *  审批按钮
	  *
	  * @param approvalAnnualKeyWork
	  * @return
	  */
	 @RequiresPermissions("annualkeyworkList:yx_annualkeyworkList:approval")
	 @Transactional//事务处理注解
	 @RequestMapping(value = "/approval", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> approvalaction(@RequestBody ApprovalAnnualKeyWork approvalAnnualKeyWork) {
		 Date date = new Date();
		 approvalAnnualKeyWork.setApprovalMonth(String.valueOf(date.getMonth()+1));
		 System.out.println(approvalAnnualKeyWork);
		 annualKeyWorkService.saveApprovalKeyWork(approvalAnnualKeyWork);
		 return Result.OK(Constants.REPORT_SUCCESS);
	 }

}
